package com.hmall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author：cxl
 * @Package：com.hmall.filter
 * @Project：hmall-micro1
 * @name：AuthGlobalFilter
 * @Date：2025/11/13 11:09
 * @Filename：AuthGlobalFilter
 */
@Component
@Slf4j
@RequiredArgsConstructor
/**
 * 网关过滤器
 */
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求路径
        //获取响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求路径
        String path = request.getURI().getPath();
        log.info("请求路径{}", path);
        //判断白名单
        List<String> excludePaths = authProperties.getExcludePaths();
        if (excludePaths.contains(path)) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("Authorization");
        if (StrUtil.isNotEmpty(token)) {
            //如果不为解析token
            try {
                Long userId = jwtTool.parseToken(token);
                //转换请求头
                log.info("过滤器{}", userId);
                request.mutate().header("user-info", String.valueOf(userId));

                return chain.filter(exchange);


            } catch (Exception e) {
                log.error("解析token失败", e);
            }
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
